package com.example.foodwebbackend.controller;

import com.example.foodwebbackend.dto.ApiResponse;
import com.example.foodwebbackend.entity.User;
import com.example.foodwebbackend.entity.UserRating;
import com.example.foodwebbackend.service.UserRatingService;
import com.example.foodwebbackend.service.UserService;
import com.example.foodwebbackend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class UserReviewController {

    @Autowired
    private UserRatingService userRatingService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取用户评价列表（分页）
     */
    @GetMapping("/reviews/user")
    public ApiResponse<Map<String, Object>> getUserReviews(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestHeader("Authorization") String token) {
        try {
            // 从token获取用户ID
            String jwt = token.substring(7); // 移除 "Bearer "
            String username = jwtUtil.getUsernameFromToken(jwt);
            User user = userService.findByUsername(username);
            
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            Map<String, Object> result = userRatingService.getUserReviews(user.getUserId(), page, size);
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取评价列表失败: " + e.getMessage());
        }
    }

    /**
     * 添加评价
     */
    @PostMapping("/reviews")
    public ApiResponse<UserRating> addReview(
            @RequestBody UserRating userRating,
            @RequestHeader("Authorization") String token) {
        try {
            // 从token获取用户ID
            String jwt = token.substring(7);
            String username = jwtUtil.getUsernameFromToken(jwt);
            User user = userService.findByUsername(username);
            
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            userRating.setUserId(user.getUserId());
            UserRating result = userRatingService.addReview(userRating);
            return ApiResponse.success("评价添加成功", result);
        } catch (Exception e) {
            return ApiResponse.error("添加评价失败: " + e.getMessage());
        }
    }

    /**
     * 删除评价
     */
    @DeleteMapping("/reviews/{ratingId}")
    public ApiResponse<?> deleteReview(
            @PathVariable Integer ratingId,
            @RequestHeader("Authorization") String token) {
        try {
            // 从token获取用户信息验证权限
            String jwt = token.substring(7);
            String username = jwtUtil.getUsernameFromToken(jwt);
            User user = userService.findByUsername(username);
            
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            boolean success = userRatingService.deleteReview(ratingId);
            if (success) {
                return ApiResponse.success("评价删除成功");
            } else {
                return ApiResponse.error("删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error("删除评价失败: " + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/user/change-password")
    public ApiResponse<?> changePassword(
            @RequestBody Map<String, String> request,
            @RequestHeader("Authorization") String token) {
        try {
            String currentPassword = request.get("currentPassword");
            String newPassword = request.get("newPassword");
            
            if (currentPassword == null || newPassword == null) {
                return ApiResponse.error("密码不能为空");
            }
            
            // 从token获取用户信息
            String jwt = token.substring(7);
            String username = jwtUtil.getUsernameFromToken(jwt);
            User user = userService.findByUsername(username);
            
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            // 验证当前密码
            if (!currentPassword.equals(user.getPassword())) {
                return ApiResponse.error("当前密码错误");
            }
            
            // 更新密码
            user.setPassword(newPassword);
            userService.updateUser(user);
            
            return ApiResponse.success("密码修改成功");
        } catch (Exception e) {
            return ApiResponse.error("密码修改失败: " + e.getMessage());
        }
    }
} 